<template>
  <div class="dialog_box">
    <el-dialog v-model="visible" width="900px" :title="`【${processData.name}】 流程的规则配置`" @closed="onClose">
      <el-tabs v-model="tabIndex" tab-position="left">
        <el-tab-pane v-for="(item, index) in processData.stages" :key="item.id" :label="item.name" :name="index">
          <div class="change_type">
            <span class="change_type_name">变更阶段的条件:</span>
            <el-radio-group v-model="formData.data[index].change_type" :disabled="index === 0">
              <el-radio :label="1">规则设定</el-radio>
              <el-radio :label="2">手动设置</el-radio>
            </el-radio-group>
          </div>
          <template v-if="formData.data[index].change_type == 1">
            <div class="rules">
              <div class="rules_item">
                <el-switch v-model="formData.data[index].rule_type" :active-value="1" :inactive-value="2" active-text="且" inactive-text="或" class="ml-2" inline-prompt />
              </div>
              <div class="rules_item" v-for="(ruleItem, ruleIndex) in formData.data[index].rules" :key="ruleItem.code">
                <span class="rules_item_name">{{ `规则${ruleIndex + 1}：` }}</span>
                <el-cascader ref="cascaderRef" v-model="formData.data[index].rules[ruleIndex].code" :options="rulesData" :props="defaultProps" @change="handleChange">
                  <template #default="{ node, data }">
                    <div @click="onCascader(data, ruleIndex)"> {{ data.name }}</div>
                  </template>
                </el-cascader>
                <span v-if="selectOptions[index][ruleIndex]?.mode.type == 'string'" class="rules_item_desc">{{ selectOptions[index][ruleIndex]?.mode.val.label }}</span>
                <el-select v-if="selectOptions[index][ruleIndex]?.mode?.type == 'select'" v-model="formData.data[index].rules[ruleIndex].mode" class="mode_select" placeholder="请选择">
                  <el-option v-for="item in selectOptions[index][ruleIndex]?.mode.val" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
                <el-select v-if="selectOptions[index][ruleIndex]?.option.type == 'select'" v-model="formData.data[index].rules[ruleIndex].val" class="mode_select" placeholder="请选择">
                  <el-option v-for="(item, opI) in selectOptions[index][ruleIndex]?.option.val" :key="item.value" :label="item.label" :value="item.value" :disabled="opI >= tabIndex && selectOptions[index][ruleIndex]?.code == 'business_stage'" />
                </el-select>
                <el-input-number v-if="selectOptions[index][ruleIndex]?.option.type == 'number'" v-model="formData.data[index].rules[ruleIndex].val" class="val_input" :min="1" controls-position="right" />
              </div>
              <div class="rules_item">
                <el-button @click="onAddRule">添加规则</el-button>
              </div>
            </div>
          </template>
          <template v-if="index > 0">
            <div class="audit_switch">
              <span class="audit_switch_name">审核机制:</span>
              <el-switch v-model="formData.data[index].audit_switch" :active-value="2" :inactive-value="1" :disabled="index === processData.stages.length - 2" />
              <span v-if="index != processData.stages.length - 1" class="audit_switch_desc">开启后，只有审核通过之后才可变更为赢单，期间该客户阶段为 “赢单待审核”</span>
              <span v-else class="audit_switch_desc">开启后，只有审核通过之后才可变更为输单，期间该客户阶段为 “输单待审核”</span>
            </div>
            <div v-if="formData.data[index].audit_switch == 2" class="audit_ids">
              <span class="audit_ids_name"> 审核人: </span>
              <div class="form-staffs">
                <div class="staffs">
                  <el-tag v-for="item in employees[index]" :key="item.name" class="staffs_item" :closable="true" @close="handleClose(item)" :type="item.id">
                    {{ item.name }}
                  </el-tag>
                </div>
              </div>
              <el-button @click="openDepart('BELONG_UID')">选择员工</el-button>
            </div>
            <div v-if="index == processData.stages.length - 1" class="audit_switch">
              <span class="audit_switch_name">输单原因:</span>
              <el-switch v-model="formData.data[index].lose_switch" disabled :active-value="2" :inactive-value="1" />
              <span class="audit_switch_desc">开启后，设置输单前必须选择输单原因</span>
            </div>
          </template>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="onClose" >取消</el-button>
          <el-button @click="onSubmit" type="primary">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
  <ZWDepart ref="DepartRef" @submit="getDepart" />
</template>

<script setup lang="ts">
  import ZWDepart from '@//components/ZWDepart.vue'
  import { geRuleDetail, getWorkflowRules, WorkflowSettingRules } from '@/api/salesleads/salesmanagement/business'
  import { getSetionId, IsNotEmpty } from '@/utils/utils'
  import { ElMessage } from 'element-plus'
  import { ref } from 'vue'
  import { defineEmits } from 'vue'
  const emit = defineEmits(['submit'])
  const onClose = () => {
    visible.value = false
  }
  const tabIndex = ref(0) // 当前阶段
  const ruleI = ref<any>([]) // 当前选择的规则项
  const visible: any = ref(false)
  const DepartRef = ref<any>() // 部门弹框类型
  const cascaderRef = ref<any>(null) // 部门弹框类型
  const processData = ref({
    stages: []
  })
  const formData = ref<any>({
    workflow_id: '', //阶段id
    data: [
      // {
      //   rules: [
      //     {
      //       code: '', //code
      //       type: '', //类型 1：订单 2：客户
      //       mode: '', //计算方式
      //       val: '' //值
      //     }
      //   ],
      //   stage_id: '',
      //   audit_switch: 1, //审核机制 1：关闭 2：开启
      //   lose_switch: 1, //输单原因 1：关闭 2：开启
      //   rule_type: 1, //规则方式 1：且 2：或
      //   change_type: 1, //规则变更方式 1：规则设定 2：手动设定
      //   audit_ids: [] //审核人员id
      // }
    ]
  })
  const defaultProps = {
    checkStrictly: false, // 是否严格的遵守父子节点不互相关联
    emitPath: false,
    multiple: false,
    label: 'name',
    value: 'code'
  }
  const selectOptions = ref<any>([
    // [
    //   {
    //     code: '',
    //     name: '',
    //     type: '',
    //     mode: {
    //       type: 'string',
    //       val: []
    //     },
    //     option: []
    //   }
    // ]
  ])
  const cascaderNode = ref<any>({})

  const onCascader = (v: any, ruleIndex: any) => {
    console.log(v, '选中的数据')
    cascaderNode.value = v
    ruleI.value[tabIndex.value] = ruleIndex
  }

  const handleChange = (v: any) => {
    console.log(selectOptions, 'select')
    // formData.value.data[tabIndex.value].rules[ruleI.value[tabIndex.value]] = {
    //   code: '',
    //   type: '',
    //   mode: '',
    //   val: ''
    // }
    selectOptions.value[tabIndex.value][ruleI.value[tabIndex.value]] = cascaderNode.value
    formData.value.data[tabIndex.value].rules[ruleI.value[tabIndex.value]].type = selectOptions.value[tabIndex.value][ruleI.value[tabIndex.value]].type
    if (selectOptions.value[tabIndex.value][ruleI.value[tabIndex.value]].mode?.type == 'string') {
      formData.value.data[tabIndex.value].rules[ruleI.value[tabIndex.value]].mode = selectOptions.value[tabIndex.value][ruleI.value[tabIndex.value]].mode.val.value
    }
  }
  const onAddRule = () => {
    selectOptions.value[tabIndex.value].push({
      type: '',
      mode: {
        type: 'string',
        val: [{ value: '=', label: '为' }]
      },
      option: { val: [] }
    })
    formData.value.data[tabIndex.value].rules.push({
      code: '', //code
      type: '', //类型 1：订单 2：客户
      mode: '', //计算方式
      val: '' //值
    })
  }
  //打开新建选择人
  const employees = ref([[]])
  const openDepart = (type: string) => {
    DepartRef.value.selectedMember = [...employees.value[tabIndex.value]]
    DepartRef.value.departVisble = true
  }
  // 获取部门成员
  const getDepart = (res: any) => {
    employees.value[tabIndex.value] = res
    formData.value.data[tabIndex.value].audit_ids = getSetionId('id', employees.value[tabIndex.value])
    console.log('获取部门成员', res)
  }
  // 员工移除
  const handleClose = (tag: any) => {
    employees.value[tabIndex.value] = employees.value[tabIndex.value].filter((item: any) => item.id !== tag.id)
    formData.value.data[tabIndex.value].audit_ids = getSetionId('id', employees.value[tabIndex.value])
    DepartRef.value.removeItem(tag)
  }
  const onDelete = (index: any) => {
    formData.value.data[tabIndex.value].stages.splice(index, 1)
  }
  const onSubmit = () => {
    if (
      !formData.value.data.every((item: any) => {
        let flag = true
        if (item.change_type == 1 && item.audit_switch == 2 && !item.audit_ids.length) {
          flag = false
        }
        return flag
      })
    ) {
      ElMessage.warning('请选择审核人员')
      return
    }
    // const valiDate = formData.value.data[tabIndex.value].rules.every((item: any) => Object.values(item).every((it) => it != ''))
    const valiDate = formData.value.data[tabIndex.value].rules.every((item: any) => !!item.code && !!item.mode)
    if (valiDate) {
      WorkflowSettingRules(formData.value).then((res: any) => {
        ElMessage.success('规则配置成功')
        visible.value = false
      })
    } else {
      ElMessage.warning('请配置完所有的规则项')
    }
  }
  const rulesData = ref([])
  const getRules = () => {
    getWorkflowRules({ workflow_id: formData.value.workflow_id }).then((res: any) => {
      console.log(res, '------规则配置-------')
      rulesData.value = res
      getLook()
    })
  }
  const onRulesDShow = (row: any) => {
    console.log(row, '------------')
    visible.value = true
    processData.value = row
    formData.value.workflow_id = row.id
    for (let i = 0; i < processData.value.stages.length; i++) {
      formData.value.data.push({
        rules: [
          {
            code: '', //code
            type: '', //类型 1：订单 2：客户
            mode: '', //计算方式
            val: '' //值
          }
        ],
        stage_id: processData.value.stages[i].id,
        audit_switch: 2, //审核机制 1：关闭 2：开启
        lose_switch: 2, //输单原因 1：关闭 2：开启
        rule_type: 1, //规则方式 1：且 2：或
        change_type: 1, //规则变更方式 1：规则设定 2：手动设定
        audit_ids: [] //审核人员id
      })
      selectOptions.value.push([
        {
          code: '',
          name: '',
          type: '',
          mode: {
            type: '',
            val: []
          },
          option: []
        }
      ])
      employees.value.push([])
    }
    formData.value.data[processData.value.stages.length - 1].audit_switch = 1
    formData.value.data[0].change_type = 2
    getRules()
  }
  const getLook = () => {
    geRuleDetail({ workflow_id: formData.value.workflow_id }).then((res: any) => {
      console.log(res, '查看规则')
      formData.value.data = res.list1
      selectOptions.value = res.list2
      employees.value = res.list3.map((item: any) => item.map((it: any) => ({ ...it, type: 'user', check: true })))
    })
  }
  defineExpose({
    onRulesDShow,
    processData
  })
</script>

<style scoped lang="scss">
  .dialog_box {
    :deep(.el-dialog) {
      .el-dialog__header {
        border-bottom: 1px solid #eaeaea;
      }
      .el-dialog__body {
        position: relative;
        padding: 0 24px;
        border-bottom: 1px solid #eaeaea;
        // &::before {
        //   content: '';
        //   height: 100%;
        //   position: absolute;
        //   left: 118px;
        //   border-left: 2px solid #e4e7ed;
        // }
        .change_type {
          display: flex;
          align-items: center;
          margin-left: 20px;
          .change_type_name {
            margin-right: 10px;
          }
        }
        .rules {
          padding: 10px;
          padding-bottom: 0;
          margin-bottom: 16px;
          margin-left: 20px;

          border: 1px solid #eaeaea;
          .rules_item {
            display: flex;
            align-items: center;
            margin-bottom: 16px;
            .rules_item_name {
              margin-right: 10px;
            }
            .rules_item_desc {
              margin-left: 10px;
            }
            .mode_select {
              width: 100px;
              margin: 0 10px;
            }
            .val_input {
              width: 100px;
            }
          }
        }
        .audit_switch {
          display: flex;
          align-items: center;
          margin-bottom: 16px;
          margin-left: 20px;
          .audit_switch_name {
            margin-right: 10px;
          }
          .audit_switch_desc {
            margin-left: 10px;
            font-size: 14px;
            color: #ff6b00;
          }
        }
        .audit_ids {
          display: flex;
          align-items: center;
          margin-bottom: 16px;
          margin-left: 20px;
          .audit_ids_name {
            margin-right: 10px;
          }
        }
      }
    }
    // 员工选择
    .form-staffs {
      display: flex;
      .title {
        margin-right: 12px;
      }

      .staffs {
        &_item {
          height: 22px;
          line-height: 22px;
          margin-right: 6px;
          // padding: 0;
          color: #35383a;
          border: 1px solid #fffaf9;
          border-radius: 1px 1px 1px 1px;
          background: #fffaf9;
        }

        :deep .el-tag .el-icon {
          width: 12px;
          height: 12px;
          color: #ffffff;
          background: #d9d9d9;
        }

        :deep .el-tag .el-icon svg {
          margin: 0px;
        }

        :deep .el-tag .el-tag__close:hover {
          background: #d9d9d9;
        }
        :deep span.el-tag.el-tag--light.staffs_item:before {
          content: '';
          display: inline-block;
          width: 10px;
          height: 11px;
          background: url('@/assets/image/LiveCode/people_icon.png') center/100% no-repeat;
          margin-right: 10px;
        }
      }
    }
  }
</style>
